package com.aipp.mall.h5.service;

import com.aipp.mall.common.exception.ServerException;
import com.aipp.mall.common.model.Query;
import com.aipp.mall.common.utils.SecurityUtil;
import com.aipp.mall.h5.domain.entity.CouponActivity;
import com.aipp.mall.h5.domain.entity.MemberCoupon;
import com.aipp.mall.h5.domain.vo.CouponActivityVO;
import com.aipp.mall.h5.mapper.CouponActivityMapper;
import com.aipp.mall.h5.mapper.MemberCouponMapper;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import org.dromara.hutool.core.collection.CollUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 优惠券活动表Service业务层处理
 *
 * @author zcc
 */
@Service
public class CouponActivityService {

    @Resource
    private CouponActivityMapper couponActivityMapper;

    @Resource
    private MemberCouponMapper memberCouponMapper;


    public CouponActivityVO getDetail(Long id) {
        CouponActivity couponActivity = couponActivityMapper.selectById(id);
        CouponActivityVO res = new CouponActivityVO();
        BeanUtils.copyProperties(couponActivity, res);
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", SecurityUtil.getLocalMember().getId()).eq("coupon_activity_id", id);
        Long count = memberCouponMapper.selectCount(queryWrapper);
        res.setCanGet(count == null || count < couponActivity.getUserLimit());
        return res;
    }

    public IPage<CouponActivityVO> selectListByH5(Query query) {
        QueryWrapper<CouponActivity> qw = new QueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        qw.lt("begin_time", now).gt("end_time", now);
        IPage<CouponActivity> page = couponActivityMapper.selectPage(Page.of(query.getPage(), query.getSize()), qw);
        if (CollUtil.isEmpty(page.getRecords())) {
            return new Page<>();
        }
        //看用户已领取的张数
        Set<Long> ids = page.getRecords().stream().map(CouponActivity::getId).collect(Collectors.toSet());
        Map<Long, Integer> countMap = memberCouponMapper.countGetCoupon(ids, SecurityUtil.getLocalMember().getId()).stream()
                                                        .collect(Collectors.toMap(CouponActivityVO::getId, CouponActivityVO::getGetCount));

        return page.convert((it) -> {
            CouponActivityVO vo = new CouponActivityVO();
            BeanUtils.copyProperties(it, vo);
            Integer integer = countMap.get(it.getId());
            if (integer == null || integer < it.getUserLimit()) {
                vo.setGetCount(integer == null ? 0 : integer);
                vo.setCanGet(true);
            } else {
                vo.setGetCount(integer);
                vo.setCanGet(false);
            }
            return vo;
        });
    }

    @Lock4j(name = "h5_receive_coupon:", keys = "#id")
    @Transactional(rollbackFor = Exception.class)
    public Boolean receiveCoupon(Long id) {
        CouponActivity couponActivity = couponActivityMapper.selectById(id);
        if (couponActivity == null) {
            throw new ServerException("未找到活动");
        }
        //判断有没有余量
        if (couponActivity.getLeftCount() < 1) {
            throw new ServerException("活动已没有余额");
        }
        //判断时间有没有超
        LocalDateTime now = LocalDateTime.now();
        if (couponActivity.getBeginTime().isAfter(now) || couponActivity.getEndTime().isBefore(now)) {
            throw new ServerException("活动已过期");
        }
        Long memberId = SecurityUtil.getLocalMember().getId();
        //判断领的有没有超
        QueryWrapper<MemberCoupon> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("member_id", memberId).eq("coupon_activity_id", id);
        Long count = memberCouponMapper.selectCount(queryWrapper);
        if (count != null && count >= couponActivity.getUserLimit()) {
            throw new ServerException("您已达到领取额度");
        }
        //兑换券
        couponActivityMapper.receiveCoupon(id);
        int saveCount = saveMemberCoupon(couponActivity, memberId);
        return saveCount > 0;
    }

    private int saveMemberCoupon(CouponActivity activity, Long memberId) {
        MemberCoupon memberCoupon = new MemberCoupon();
        memberCoupon.setCouponActivityId(activity.getId());
        memberCoupon.setTitle(activity.getTitle());
        memberCoupon.setUseScope(activity.getUseScope());
        memberCoupon.setProductIds(activity.getProductIds());
        memberCoupon.setCouponAmount(activity.getCouponAmount());
        memberCoupon.setMinAmount(activity.getMinAmount());
        memberCoupon.setUseIntegral(activity.getUseIntegral());
        memberCoupon.setCouponType(activity.getCouponType());
        memberCoupon.setBeginTime(LocalDateTime.now());
        memberCoupon.setEndTime(activity.getEndTime());
        memberCoupon.setCreateTime(LocalDateTime.now());
        memberCoupon.setMemberId(memberId);
        return memberCouponMapper.insert(memberCoupon);
    }

}
